package utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by Administrator on 2015/12/19 0019.
 */
public class PinyinUtils {
    /**
     * 将传入的字符串转换成拼音
     *
     * @param str
     * @return
     */
    public static String getPinyin(String str) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//不要音调
        StringBuilder sb = new StringBuilder();

        //通过char得到stringarray;
        char[] strChar = str.toCharArray();
        for (int i = 0; i < strChar.length; i++) {
            char c = strChar[i];
            if (Character.isWhitespace(c)) {//如果是空格，就跳过
                continue;
            }
            if (c < 128 && c >= -127) {
                sb.append(c);//不是中文
            } else {
                String s = "";
                try {
                    s = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
                    sb.append(s);
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                    sb.append(s);
                }
            }

        }

        return sb.toString().toUpperCase();
    }
}
